package astar;


public class DistanceCalculator {
	
	public double getDistance(Node n1, Node n2) {
		
		double val =  (double) Math.sqrt(
					Math.pow((double)AStarConstants.UNIT_SIZE*(n1.x - n2.x), 2) +
					Math.pow((double)AStarConstants.UNIT_SIZE*(n1.y - n2.y), 2)
					 );
		//double so as to make sure we get the same value as compared to other langues
		//System.out.println(String.format("(%d, %d) (%d, %d) "+val,n1.x,n1.y,n2.x,n2.y));
		return val;
	}

	public Node[] getNeighbors(Node node, Area area) {
		Node leftN = null;
		Node topN = null;
		Node rightN = null;
		Node bottomN = null;
		Node leftUpperN = null;
		Node rightUpperN = null;
		Node rightLowerN = null;
		Node leftLowerN = null;

		int nCount = 0;
		if(node.x > 0 && area.getTerrainAt(node.x-1, node.y) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			leftN = new Node(node.x-1,node.y);
		}
		if(node.x < area.width-1 && area.getTerrainAt(node.x+1, node.y) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			rightN = new Node(node.x+1,node.y);
		}
		if(node.y > 0 && area.getTerrainAt(node.x, node.y-1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			topN = new Node(node.x, node.y-1);
		}
		if(node.y < area.height-1 && area.getTerrainAt(node.x, node.y+1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			bottomN = new Node(node.x, node.y+1);
		}

		if(node.x > 0 && node.y > 0 && area.getTerrainAt(node.x-1, node.y-1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			leftUpperN = new Node(node.x-1,node.y-1);
		}
		if(node.x > 0 && node.y < area.height-1 && area.getTerrainAt(node.x-1, node.y+1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			leftLowerN  = new Node(node.x-1,node.y+1);
		}
		if(node.x < area.width-1 && node.y > 0 && area.getTerrainAt(node.x+1, node.y-1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			rightUpperN = new Node(node.x+1,node.y-1);
		}
		if(node.x < area.width-1 && node.y < area.height-1 && area.getTerrainAt(node.x+1, node.y+1) != AStarConstants.TERRAIN_IMPASSABLE) {
			nCount++;
			rightLowerN  = new Node(node.x+1,node.y+1);
		}

		Node[] neighbors = new Node[nCount];

		int posCount = 0;

		if(leftN!=null) {
			neighbors[posCount] = leftN;
			posCount++;
		}

		if(topN!=null) {
			neighbors[posCount] = topN;
			posCount++;
		}

		if(rightN!=null) {
			neighbors[posCount] = rightN;
			posCount++;
		}

		if(bottomN!=null) {
			neighbors[posCount] = bottomN;
			posCount++;
		}

		if(leftUpperN!=null) {
			neighbors[posCount] = leftUpperN;
			posCount++;
		}

		if(leftLowerN!=null) {
			neighbors[posCount] = leftLowerN;
			posCount++;
		}

		if(rightUpperN!=null) {
			neighbors[posCount] = rightUpperN;
			posCount++;
		}

		if(rightLowerN!=null) {
			neighbors[posCount] = rightLowerN;
			posCount++;
		}

		return neighbors;
	}
}
